// ignore_for_file: file_names, must_be_immutable, constant_identifier_names, slash_for_doc_comments, avoid_unnecessary_containers, prefer_const_constructors, unnecessary_cast, sized_box_for_whitespace, prefer_function_declarations_over_variables, overridden_fields, annotate_overrides, prefer_const_literals_to_create_immutables, unnecessary_null_comparison, deprecated_member_use, unused_import, avoid_print, unnecessary_brace_in_string_interps

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'IFFR.dart';

/**刷新接口 */
abstract class IFFRefresh {
  /**添加刷新组件 */
  Widget ffWidget(BuildContext ctx, Widget child);
  /**能否刷新头部 */
  bool? ffCanRefreshHead();
  /**能否加载更多 */
  bool? ffCanRefreshFoot();

  R ffRefresh(bool isHead);

  /**刷新控制 */

  /// 头部
  /**请求刷新 */
  Future<void> ffRequestRefresh();
  /**刷新成功 */
  ffRefreshCompleted();

  /// 尾部
  /**加载成功 */
  ffLoadComplete();
}


/**列表页 */
class MFFRefresh implements IFFRefresh {
  ///刷新控件
  RefreshController refreshController =
      RefreshController(initialRefresh: false);

  @override
  Widget ffWidget(BuildContext ctx, Widget child) {
    return SmartRefresher(
      enablePullDown: ffCanRefreshHead() ?? false,
      enablePullUp: ffCanRefreshFoot() ?? false,
      header: ClassicHeader(),
      footer: CustomFooter(
        builder: (BuildContext context, LoadStatus? mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = Text("上拉加载更多");
          } else if (mode == LoadStatus.loading) {
            body = CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = Text("加载出错，请重试");
          } else if (mode == LoadStatus.canLoading) {
            body = Text("松开加载更多");
          } else {
            body = Text("没有数据了");
          }
          return Container(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: refreshController,
      onRefresh: () {
        ffRefresh(true);
      },
      onLoading: () {
        ffRefresh(false);
      },
      child: child,
    );
  }

  @override
  bool? ffCanRefreshFoot() {
    return true;
  }

  @override
  bool? ffCanRefreshHead() {
    return true;
  }

  @override
  R ffRefresh(bool isHead) {
    print("ffRefresh isHead = ${isHead}");
    if (isHead) {
      ffRefreshCompleted();
    } else {
      ffLoadComplete();
    }
    return R();
  }

  @override
  Future<void> ffRequestRefresh() async {
    await refreshController.requestRefresh();
  }

  @override
  ffRefreshCompleted() {
    refreshController.refreshCompleted();
  }

  @override
  ffLoadComplete() {
    // refreshController.loadComplete();
    refreshController.loadNoData();
  }
}